package com.supor.aiot.common.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;

import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.utils.ToastUtils;
import com.mpaas.mas.adapter.api.MPLogger;
import com.mpaas.nebula.adapter.api.MPTinyHelper;
import com.supor.aiot.common.R;
import com.supor.aiot.common.base.BaseConfigActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.databinding.ActivityScanGuideBinding;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.ui.scan.ScanHelper;

import androidx.annotation.NonNull;

import static com.supor.aiot.common.app.Constants.SETTING_GPS;


public class ScanGuideActivity extends BaseConfigActivity<NoViewModel, ActivityScanGuideBinding> {

    private String redirectUrl;
    private String device;
    private String page;
    private String params;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.activity_scan_guide);
        // ButterKnife.bind(this);
        // // 所需的全部权限
        // initView();
    }

    @Override
    protected int resourceId() {
        return R.layout.activity_scan_guide;
    }

    public void initView() {
        super.initView();
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());

        // 1.请打开   菜单-网络
        String tip = getString(R.string.bind_scan_guide_step1);
        SpannableString ss1 = new SpannableString(tip);
        ClickableSpan clickableSpan1 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                // Intent intent = new Intent(ScanGuideActivity.this, InputWiFiActivity.class);
                // Bundle bundle = new Bundle();
                // bundle.putInt(Constants.Key.CONFIG_TYPE, 1);
                // intent.putExtras(bundle);
                // startActivity(intent);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        ss1.setSpan(clickableSpan1, tip.indexOf("菜单"), tip.indexOf("菜单") + 5,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        ss1.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                tip.indexOf("菜单"), tip.indexOf("菜单") + 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //拿到所加图片的drawable对象
        // Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_menu, null);
        // drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        // CenterImageSpan imageSpan = new CenterImageSpan(drawable);
        // ss1.setSpan(imageSpan, 6, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        bindingView.tvStep1.setText(ss1);
        // tvStep1.setMovementMethod(LinkMovementMethod.getInstance());

        // 2.点APP下载，显示二维码
        tip = getString(R.string.bind_scan_guide_step2);
        SpannableString ss2 = new SpannableString(tip);
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                // startActivity(new Intent(ScanGuideActivity.this, InputWiFiActivity.class));
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        ss2.setSpan(clickableSpan, tip.indexOf("二维码"), tip.indexOf("二维码") + 3,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                tip.indexOf("二维码"), tip.indexOf("二维码") + 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        bindingView.tvStep2.setText(ss2);
        // tvStep2.setMovementMethod(LinkMovementMethod.getInstance());

        bindingView.btnNextStep.setOnClickListener(v -> gotoScanActivity());
        // MediaManager.getInstance().soundPoolPlay(3);
        // MediaPlayer.create(this, R.raw.beep).start();

        Intent intent = getIntent();
        page = intent.getStringExtra("page");
        redirectUrl = intent.getStringExtra("redirectUrl");
        params = intent.getStringExtra("param");
        Logc.i("redirectUrl= " + redirectUrl + ", page= " + page + ", params= " + params);
        MPLogger.setUserId("123456");
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (SETTING_GPS == requestCode) {
            if (!SystemUtils.isGpsEnabled(this)) {
                tips("打开定位失败");
            } else {
                Logc.i("============ 打开定位成功");
            }
        }/* else if (REQUEST_CODE_PHOTO == requestCode) {
            // scanFromUri(data.getData());
        }*/
    }

    private void gotoScanActivity() {
        ScanHelper.getInstance().scan(this, new ScanHelper.ScanCallback() {
            @Override
            public void onScanResult(boolean isProcessed, Intent result) {
                if (!isProcessed) {
                    // 扫码界面点击物理返回键或左上角返回键
                    return;
                }

                // 注意：本回调是在子线程中执行
                runOnUiThread(() -> {
                    if (result == null || result.getData() == null) {
                        // 扫码失败
                        return;
                    }
                    // 扫码成功
                    String url = result.getData().toString();
                    Logc.d("scan url: " + url);
                    ToastUtils.getInstance().showCustomToast(url);
                    Bundle tinyBundle = new Bundle();
                    tinyBundle.putBoolean("needAnimInTiny", true);
                    // String query = "urlType="+ Uri.encode("2")+"&redirectUrl="+Uri.encode("2021012010453410078");
                    // tinyBundle.putString("query",query); //设置参数
                    // 第一个参数为二维码的 uri，第二个参数为自定义启动参数。若无自定义启动参数则填 new Bundle()。
                    // MPTinyHelper.getInstance().launchIdeQRCode(Uri.parse(url), tinyBundle);
                    // 设备详情页

                    String query = "";
                    if (!TextUtils.isEmpty(redirectUrl)) {
                        query = query + "&redirectUrl=" + /*Uri.encode(*/redirectUrl.trim();
                    }
                    if (!TextUtils.isEmpty(params)) {
                        query = query + "&" + /*Uri.encode(*/params.trim();
                    }
                    if (GlobalDataCache.userInfo != null) {
                        query = query + "&userInfo=" + GsonUtil.getInstance().toJson(GlobalDataCache.userInfo);
                    }
                    if (query.startsWith("&")) {
                        query = query.substring(1);
                    }
                    tinyBundle.putString("query",query); //设置参数
                    if (!TextUtils.isEmpty(page)) {
                        tinyBundle.putString("page", page + "?" + query);
                    }
                    Logc.d("page: " + page);
                    Logc.d("startTiny: " + query);
                    // 第一个参数为二维码的 uri，第二个参数为自定义启动参数。若无自定义启动参数则填 new Bundle()。
                    MPTinyHelper.getInstance().launchIdeQRCode(Uri.parse(url), tinyBundle);

                    finish();
                });
            }
        });
    }
}
